import { LocalstorageDataManage } from './../common/localstoreage/localstoreageDataManage';
import { Employee } from './../models/Employee';
import { employeesRestApi, EmployeesRestApi } from './../common/http/rest-api';
import { businsessHttpServer } from './../common/http/http-server';
import { Observable, Subject, BehaviorSubject } from 'rxjs';
import { EmployeInfoStatus, EmployeeInfosManage } from './employeesInfoManage';


class Employees {
    employees: Array<Employee>;
    observable: BehaviorSubject<Array<Employee>>;
    employeesRestApi: EmployeesRestApi;
    constructor(employeesRestApi) {
        this.employeesRestApi = employeesRestApi;
        this.init();
    }

    async init() {
        this.employees = await this.employeesRestApi.getEmployees();
        this.observable = new BehaviorSubject(this.employees);
        if (!localStorage.getItem("EmployeeInfos")) {
            localStorage.setItem("EmployeeInfos", JSON.stringify(this.employees.map(x => { return { id: x.id, hasDeliveryCount: 0, status: EmployeInfoStatus.offline, turns: ['全部'], roles: x.roles } })))
        }
    }

    notify() {
        this.observable.next(this.employees);
    }

    getObservable() {
        return this.observable;
    }

    async getDishesDistributor(): Promise<Array<Employee>> { 
        //应该是有人订阅才弄到this.employees上
        let employees = await this.getEntities();
        employees = employees.filter(employee => employee.roles && employee.roles.map(role => role.name).indexOf('dishes distributor') > -1);
        if (!localStorage.getItem("EmployeeInfos")) {
            localStorage.setItem("EmployeeInfos", JSON.stringify(this.employees.map(x => { return { id: x.id, hasDeliveryCount: 0, status: EmployeInfoStatus.offline, turns: ['全部'], roles: x.roles } })))
        }
        let employeeInfos = EmployeeInfosManage.current.updateEmployeeInfosByEmployees(employees);
        return employees;
    }

    getEntities(){
        return this.employeesRestApi.getEmployees();
    }

    async getChef(){
        let employees = await this.getEntities();
        employees = employees.filter(employee => employee.roles && employee.roles.map(role => role.name).indexOf('chef') > -1);
        return employees;
    }

    addOrder(employee) {
        this.employees.push(employee);
        this.notify();
    }

    updateEmployee(employee:Employee){
        return this.employeesRestApi.updateEmployee(employee);
    }
}



export const employeesService = new Employees(employeesRestApi);